const { getCount, getOne, getAll, query } = require('../../utils/dbTools');
const tableName = 'posts';
/**
 * 获取数据总条数
 * 
*/

const postsTotal = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    const { doctorid, patientid } = req.query;
    if (!doctorid && !patientid) {
        output.code = 500;
        output.msg = "参数错误:缺少doctorid或者patientid, 必须传递其中之一";
        return res.send(output);
    }
    // 查询条件
    var map = {}
    // 如果传递了doctorid
    if (doctorid) {
        map.doctorid = doctorid;
    } else {
        map.patientid = patientid;
    }

    const result = await getCount(tableName, map);
    if (!result) {
        output.code = 500;
        output.msg = '操作失败';
    }
    output.data = result;
    res.send(output);
}

/**
 *  文章搜索
 * 
*/
const postsSearch = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    const { keyword } = req.query;
    if (!keyword) {
        output.code = 500;
        output.msg = "参数错误,缺少参数keyword";
        return res.send(output);
    }
    const sql = `select * from ${tableName} where title like '%${keyword}%'`
    const result = await query(sql, {});
    if (!result) {
        output.code = 500;
        output.msg = "操作失败";
        return res.send(output);
    }
    output.data = result;
    res.send(output);
}

/**
 *  文章列表
 * 
*/
const postsList = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    const { page, size } = req.query;

    const params = {}
    // 如果传递了分页参数, 则实现分页查询
    if (page && size) {
        params.page = page;
        params.size = size;
    }
    const result = await getAll(tableName, params);
    if (!result) {
        output.code = 500;
        output.msg = "操作失败";
        return res.send(output);
    }
    output.data = result;
    res.send(output);
}

/**
 * 获取文章详情
 * 
*/
const postsInfo = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    const { id } = req.query;
    if (!id) {
        output.code = 500;
        output.msg = "参数错误: 缺少参数id";
        return res.send(output);
    }
    const info = await getOne(tableName, { id });
    if (info) {
        output.data = info;
    } else {
        output.code = 404;
        output.msg = "文章id错误: 未查询到相关数据";
    }
    res.send(output);
}

/**
 * 更新文章详情信息: 阅读数
 * 
*/
const postsUpdate = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    const { id } = req.query;
    if (!id) {
        output.code = 500;
        output.msg = "参数错误: 缺少参数id";
        return res.send(output);
    }
    await query(`update ${tableName} set visit_count=visit_count+1 where id=${id}`)
    res.send(output);
}

module.exports = {
    postsList,
    postsTotal,
    postsInfo,
    postsSearch,
    postsUpdate
}